import { Component, OnInit } from '@angular/core';
import { NzModalRef, NzMessageService } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { OrderService } from '@core/routes-services/order.service';
import { LEVEL_APPLICATION_OPTION } from '../../../constant/dictionary';

@Component({
  selector: 'app-integral-convert-view',
  templateUrl: './convert-view.component.html',
})
export class IntegralConvertViewComponent implements OnInit {
  entity: any = {};
  validateForm: FormGroup;
  isLoading: boolean = false;
  statusOption: any [] = LEVEL_APPLICATION_OPTION;

  constructor(private fb: FormBuilder,
              private modal: NzModalRef,
              private orderService: OrderService,
              public message: NzMessageService,
  ) {
  }

  ngOnInit(): void {
    this.isLoading = true;
    this.validateForm = this.fb.group({
      name: [this.entity.name, [Validators.required, Validators.maxLength(30)]],
    });
    let that = this;
    setTimeout(function(res) {
      that.isLoading = false;
    }, 300);

  }

  submitForm(): void {
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    } else {
      this.isLoading = true;
      this.orderService.saveOrUpdateEntity(this.entity.id, this.validateForm.value).then((res) => {
        if (res.status.toString().startsWith('20')) {
          this.modal.close(true);
        } else {
          this.message.warning(res.message);
        }
        this.isLoading = false;
      }, error => {
        this.message.error(error.message ? error.message : error.error);
        this.isLoading = false;
      });
    }
  }

  close() {
    this.modal.destroy();
  }
}
